package com.ganzalang.gmall.designpatterns.composite;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * @description: 使用组合设计模式
 * @author: ganzalang
 */
@Slf4j
public class CompositePatternDemo {

    /**
     * 组合模式主要用于对层级代码进行操作
     * @param args
     */
    public static void main(String[] args) {
        Department leafDept1 = new Department("叶子节点1-1");
        Department leafDept2 = new Department("叶子节点1-2");
        Department leafDept3 = new Department("叶子节点2-1");

        Department subDept1 = new Department("子节点1");
        subDept1.getChildren().add(leafDept1);
        subDept1.getChildren().add(leafDept2);

        Department subDept2 = new Department("子节点2");
        subDept2.getChildren().add(leafDept3);

        Department parentDept = new Department("父节点");
        parentDept.getChildren().add(subDept1);
        parentDept.getChildren().add(subDept2);

        parentDept.remove();
    }


    public static class Department {
        private String name;
        private List<Department> children = new ArrayList<>();

        public Department(String name) {
            this.name = name;
        }

        public void setChildren(List<Department> children) {
            this.children = children;
        }

        public List<Department> getChildren() {
            return children;
        }

        public void remove() {
            if (children.size() > 0) {
                for (Department child : children) {
                    child.remove();
                }
            }
            log.info("删除节点" + name);
        }

    }
}
